<template>
  <div class="app-container">
    <SearchForm
      v-show="showSearch"
      v-model="queryParams"
      :options="options.formOps"
      @onQuery="getList"
    >
    </SearchForm>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col> -->

      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:user:remove']"
          >删除</el-button
        >
      </el-col> -->

      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <Table
      ref="table"
      :auto-featch="true"
      :fetch-data="fetchData"
      :options="options.table"
      actionWidth="350"
      :rowClassName="rowClassName"
    >
      <template #beforejobContent>
        <el-table-column
          label="票据号"
          align="center"
          key="billNumber"
          prop="billNumber"
          width="200"
        />
      </template>
      <template #applyCompanyId="{ row }">{{ row.applyCompany }}</template>

      <template #jobPersonnel="{ row }"> {{ row.jobPersonnelName }}</template>
      <template #monitorLocal="{ row }"> {{ row.monitorLocalName }}</template>
      <template #gasLocal="{ row }"> {{ row.gasLocalName }}</template>
      <template #jobType="{ row }"> {{ row.jobTypeName }}</template>
      <template #default>
        <el-table-column label="暂停记录" align="center" width="200">
          <template #default="{ row }">
            <el-button type="text" @click="handleDetail(row)">查看</el-button>
          </template>
        </el-table-column>
      </template>
      <template #actionButton="{ row }">
        <!-- <el-button type="text" v-if="!isExpire(row)" @click="handleStop(row)">
          {{ row.operateStatus == 1 ? "恢复" : "暂停" }}
        </el-button> -->
        <el-button type="text" @click="handleEdit(row)">作业详情</el-button>
        <el-button type="text" @click="openMap(row)">作业区域</el-button>
        <el-button
          type="text"
          @click="openPiaojuDialog(row)"
          v-hasPermi="['app:create:job:bill:list']"
          >作业票列表</el-button
        >
        <el-dropdown
          style="padding: 0 5px"
          v-hasPermi="['app:create:job:bill:by:ptw']"
          v-if="!isExpire(row)"
        >
          <el-button type="text"> 新开作业票 </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                @click="openKp(row, ele)"
                v-for="ele in showZypList(row)"
              >
                {{ ele.name }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button
          type="text"
          style="color: red"
          @click="handleDel(row)"
          v-hasPermi="['ob:plan:bill:declare:delete']"
          >删除</el-button
        >
      </template>
    </Table>
    <DialogVform
      :formJson="formJson"
      ref="dialogVform"
      @onSubmit="onSubmit"
      width="60%"
      :showButton="false"
      title="作业计划"
      :slots="[
        'custody',
        'coordinate',
        'jobPersonnel',
        'jobPersonCharge',
        'approvedBy',
        'examinationPeople',
        // 'monitorLocal',
        // 'gasLocal',
      ]"
    >
      <template #monitorLocal>
        <el-form-item label="涉及监控点位" label-position="top">
          <el-table ref="dragTable" :data="form.monitorLocal">
            <el-table-column
              label="监控点位名称"
              prop="monitorName"
              :show-overflow-tooltip="true"
            />
          </el-table>
        </el-form-item>
      </template>
      <template #gasLocal>
        <el-form-item label="涉及气体位号" label-position="top">
          <el-table ref="dragTable" :data="form.gasLocal">
            <el-table-column
              label="气体位号"
              prop="bitNumber"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="安装位置"
              prop="installAddress"
              :show-overflow-tooltip="true"
            />
          </el-table>
        </el-form-item>
      </template>
      <template #jobPersonnel>
        <el-form-item label="作业人员" label-position="right">
          <el-table ref="dragTable" :data="form.jobPersonnel">
            <el-table-column
              label="姓名"
              align="center"
              key="name"
              prop="name"
            />
            <!-- <el-table-column
              label="证书号"
              align="center"
              key="zsh"
              prop="zsh"
            /> -->

            <el-table-column label="人员类型" align="center">
              <template #default="{ row }">
                {{ row.type == "in" ? "内部人员" : "外部人员" }}
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </template>
      <template v-for="(item, key) of slots" #[key]>
        <el-form-item :label="item" :prop="key" label-position="right">
          <el-input v-model="form[key]" readonly @click="onInnerOpen(key)">
          </el-input>
        </el-form-item>
      </template>
    </DialogVform>
    <el-dialog v-model="outerVisible" width="90%" title="特殊作业票列表">
      <template #default>
        <paojuListVue
          ref="inner"
          :showFuzhi="isExpire(parentNode)"
        ></paojuListVue>
      </template>
    </el-dialog>
    <MapDialog
      ref="map"
      mapId="zypgl"
      @change="mapChange"
      :useButton="false"
    ></MapDialog>
    <ZypInput ref="zypDialog"></ZypInput>
    <el-dialog v-model="stopVisible" width="90%" title="暂停恢复记录">
      <Inner ref="stopref" :parentNode="parentNode2"></Inner>
    </el-dialog>
    <el-dialog v-model="stopDialog" width="45%" title="暂停/恢复">
      <el-form ref="stopRef" :model="stopForm" :rules="stopRules">
        <!-- <h3 class="title">后台管理系统</h3> -->、
        <el-form-item prop="operateTime" label="时间">
          <el-date-picker
            type="datetime"
            v-model="stopForm.operateTime"
            clearable
            style="width: 100%"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item prop="remark" label="描述">
          <el-input
            v-model="stopForm.remark"
            type="textarea"
            size="large"
            placeholder="描述"
          >
          </el-input>
        </el-form-item>

        <el-form-item style="width: 100%">
          <div style="width: 100%; display: flex; justify-content: flex-end">
            <el-button :loading="loading" type="primary" @click="submitStopForm"
              >确认
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import Table from "@/components/Table/index.vue";
import SearchForm from "@/components/searchForm/index";
import DialogVform from "@/components/dialogVform/index";
import { apis as APIS, stopAndRestart } from "@/api/zygl/zysb.js";
import formJson from "./components/options.json";
import paojuListVue from "./components/paojuList.vue";
import ZypInput from "./components/input.vue";
import { useAsyncData, useFormJsonNew } from "@/views/hooks/useAsyncData.js";
import MapDialog from "@/components/mapDialog/index";
import { nextTick } from "vue";
import Inner from "./components//inner.vue";

const { proxy } = getCurrentInstance();
const ops = useFormJsonNew(formJson, {
  sort: ["jobContent", "local"],
  sortable: [],
});

const options = reactive({
  table: ops,
  formOps: ops.filter((i) =>
    [
      "riskLevel",
      "applyCompany",
      "degree",
      "jobPlanStartDate",
      "izManual",
      "billNumber",
      "local",
      "workShop",
      "declareType",
    ].includes(i.prop)
  ),
});
const slots = ref({
  custody: "属地监护人",
  coordinate: "施工协调员",
  jobPersonCharge: "工作负责人",
  approvedBy: "现场批准人",
  examinationPeople: "措施审查人",
});
const showSearch = ref(true);
const outerVisible = ref(false);
const dialogVform = ref();

const table = ref();

const showButton = ref(true);
const plugAdd = () => {
  showButton.value = true;
};
const plugEdit = (row) => {
  showButton.value = false;
  form.value.applyCompanyId = row.applyCompanyId;
  form.value.jobPersonnel = row.jobPersonnel;
  form.value.monitorLocal = row.monitorLocal;
  form.value.gasLocal = row.gasLocal;
  form.value.jobType = row.jobType;
  form.value.custody = row.custody;
  form.value.coordinate = row.coordinate;
  form.value.jobPersonnel = row.jobPersonnel;
  form.value.jobPersonCharge = row.jobPersonCharge;
  form.value.approvedBy = row.approvedBy;
  form.value.examinationPeople = row.examinationPeople;
  form.value.custodyId = row.custodyId;
  form.value.coordinateId = row.coordinateId;
  form.value.jobPersonnelId = row.jobPersonnelId;
  form.value.jobPersonChargeId = row.jobPersonChargeId;
  form.value.approvedById = row.approvedById;
  form.value.examinationPeopleId = row.examinationPeopleId;
};
const formatList = (list) => {
  return list.map((item) => {
    let jobPersonnel = [];
    let monitorLocal = [];
    let gasLocal = [];
    try {
      jobPersonnel = JSON.parse(item.jobPersonnel) || [];
    } catch (error) {
      jobPersonnel = [];
    }
    try {
      monitorLocal = JSON.parse(item.monitorLocal) || [];
    } catch (error) {
      monitorLocal = [];
    }
    try {
      gasLocal = JSON.parse(item.gasLocal) || [];
    } catch (error) {
      gasLocal = [];
    }
    return {
      ...item,
      jobPersonnel,
      monitorLocal,
      gasLocal,
      jobType: (item.jobType && item.jobType.split(",")) || [],
      jobPersonnelName: jobPersonnel.reduce((acc, item) => {
        return (acc += item.name);
      }, ""),
      monitorLocalName: monitorLocal.reduce((acc, item) => {
        return (acc += item.monitorName);
      }, ""),
      gasLocalName: gasLocal.reduce((acc, item) => {
        return (acc += item.bitNumber);
      }, ""),
      jobTypeName: item.jobType,
    };
  });
};
const parentNode = ref({});
const inner = ref();
const openPiaojuDialog = (row) => {
  outerVisible.value = true;
  parentNode.value = row;
  nextTick().then(() => {
    inner.value.changeParent(row);
  });
};
const {
  onSubmit,
  fetchData,
  handleAdd,
  handleEdit,
  getList,
  handleDel,
  queryParams,
  dialogType,
  form,
} = useAsyncData({
  APIS,
  formJson,
  dialogVform,
  table,
  proxy,
  plugEdit,
  formatList,
});
const map = ref();
const points = ref([]);
const openMap = (row) => {
  if (row && row.drawArea) {
    map.value.open(JSON.parse(row.drawArea));
    return;
  }
  map.value.open([]);
};
const mapChange = (data) => {
  points.value = data;
};

// 作业票相关逻辑
const zypTypes = [
  {
    name: "吊装安全作业票",
    type: "1",
    keyWord: "吊装",
  },
  {
    name: "动火安全作业票",
    type: "2",
    keyWord: "动火",
  },
  {
    name: "高处安全作业票",
    type: "3",
    keyWord: "高处",
  },
  {
    name: "动土安全作业票",
    type: "4",
    keyWord: "动土",
  },
  {
    name: "临时用电作业票",
    type: "5",
    keyWord: "用电",
  },
  {
    name: "动用射线安全作业票",
    type: "6",
    keyWord: "射线",
  },
  {
    name: "断路安全作业票",
    type: "7",
    keyWord: "断路",
  },
  {
    name: "盲板抽堵安全作业票",
    type: "8",
    keyWord: "盲板",
  },
  {
    name: "设备开孔安全作业票",
    type: "9",
    keyWord: "设备",
  },
  {
    name: "受限空间安全作业票",
    type: "10",
    keyWord: "受限空间",
  },
];
const showZypList = (row) => {
  let zypList = zypTypes.filter((item) =>
    row.jobTypeName.includes(item.keyWord)
  );
  if (zypList.length == 0) {
    return zypTypes;
  } else {
    return zypList;
  }
};
const zypDialog = ref();
const openKp = (row, ele) => {
  zypDialog.value.open({
    billNumber: row.billNumber,
    billType: ele.type,
    pid: row.id,
  });
};
const isExpire = (row) => {
  const planTime = Date.parse(row.jobPlanEndDate + " " + row.jobPlanEndTime);
  const nowDate = Date.now();
  if (nowDate > planTime) {
    return true;
  }
  return false;
};
const rowClassName = ({ row, rowIndex }) => {
  if (row.cancel === true) {
    return "red";
  } else {
    return "";
  }
};

// 暂停、恢复
const stopVisible = ref(false);
const stopDialog = ref(false);
const stopref = ref();
const parentNode2 = ref({});
const handleDetail = (row) => {
  stopVisible.value = true;
  nextTick().then(() => {
    parentNode2.value = row;
  });
};
const stopForm = ref({
  remark: "",
  operateTime: "",
  pid: "",
});
const stopRules = {
  remark: [{ required: true, trigger: "blur", message: "请输入暂停描述" }],
  operateTime: [{ required: true, trigger: "blur", message: "请选择时间" }],
};
const handleStop = (row) => {
  stopDialog.value = true;
  stopForm.value.pid = row.id;
  stopForm.value.operateStatus = row.operateStatus;
  stopForm.value.currentStatus = row.operateStatus == 1 ? 2 : 1;
};
const stopRef = ref();
const submitStopForm = async () => {
  const res = await stopRef.value.validate();
  if (res) {
    stopAndRestart
      .add({
        ...stopForm.value,
      })
      .then((res) => {
        proxy.$modal.msgSuccess("操作成功");
        stopDialog.value = false;
        getList(true);
      });
  }
};
</script>

<style lang="scss" scoped></style>
